package com.samshow.filter;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.FilterInvocation;

import javax.servlet.*;
import java.io.IOException;

/**
 * Created by Administrator on 2017/1/16.
 */
public class GatewaySecurityFilter extends AbstractSecurityInterceptor implements Filter{


    private SecurityMetadataSource securityMetadataSource;


    public GatewaySecurityFilter(SecurityMetadataSource securityMetadataSource,AccessDecisionManager accessDecisionManager,AuthenticationManager authenticationManager){
        System.out.println("GatewaySecurityFilter.............................+++++++++++++");
        this.setAccessDecisionManager(accessDecisionManager);
        this.setAuthenticationManager(authenticationManager);
        this.securityMetadataSource = securityMetadataSource;

    }


    @Override
    public Class<?> getSecureObjectClass() {
        System.out.println("getSecureObjectClass.............................+++++++++++++");
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        System.out.println("SecurityMetadataSource.............................+++++++++++++");
        return securityMetadataSource;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init.............................+++++++++++++");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter.............................+++++++++++++");
        FilterInvocation fi = new FilterInvocation( servletRequest, servletResponse, filterChain );
        invoke(fi);
    }

    public void invoke( FilterInvocation fi ) throws IOException, ServletException{
        System.out.println("filter..........................");
        InterceptorStatusToken token = super.beforeInvocation(fi);
        try{
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        }finally{
            super.afterInvocation(token, null);
        }

    }

    @Override
    public void destroy() {

    }
}
